package com.ykt.interceptor;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.kit.StrKit;
import com.ykt.exception.BusinessException;
import com.ykt.vo.ResultStatus;
import com.ykt.vo.ResultVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author long.hua
 * @version 1.0.0
 * @since 2015-12-08 23:44
 */

public class ExceptionInterceptor implements Interceptor {
    private final static Logger LOGGER = LoggerFactory.getLogger(ExceptionInterceptor.class);

    @Override
    public void intercept(Invocation inv) {
        Controller controller = inv.getController();
        try {

            inv.invoke();

        } catch (Exception e) {
            // 打印日志
            printLog(e);

            // 返回信息
            ResultVo vo = getResult(e);
            controller.renderJson(vo);
            throw e;
        }
    }

    /**
     * 记录异常日志
     * @param e 异常对象
     */
    private void printLog(Exception e) {
        // 根据异常类型记录不同级别日志
        if (e instanceof BusinessException) {
            LOGGER.warn("业务异常：", e);
        } else {
            LOGGER.error("系统异常：", e);
        }
    }

    /**
     * 格式化异常信息，用于友好响应用户
     *
     * @param e 异常对象
     * @return 异常消息
     */
    private static ResultVo getResult(Exception e) {
        int code;
        String message;

        // 取最后的异常，才是真实异常
        Throwable cause = e;
        while ((cause = e.getCause()) != null) {
            e = (Exception) cause;
        }

        //一些常见异常提示
        if (e instanceof BusinessException) {
            code = ((BusinessException) e).getCode();
            message = e.getMessage();
        } else {
            code = ResultStatus.FAILURE;
            message = e.getMessage();
        }

        //获取默认异常提示
        if (StrKit.isBlank(message)) {
            message = "系统繁忙,请稍后再试";
        }

        return new ResultVo(code, message.replaceAll("\"", "'"));
    }

}
